#ifndef SERIALWIDGET_H
#define SERIALWIDGET_H

#include <QWidget>
#include <QSerialPortInfo>
#include <QComboBox>
#include <QPushButton>
#include <QTextEdit>
#include <QCheckBox>
#include <QSpinBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QGroupBox>

// 引入业务层和数据层
#include "business/serial/serialmanager.h"
#include "models/serialconfig.h"
#include "ui/common/simplekeyboard.h"

/**
 * @brief 串口助手界面类（UI层）
 * 
 * 职责：
 * 1. 负责界面布局和显示
 * 2. 响应用户操作
 * 3. 将用户操作转发给业务层（SerialManager）
 * 4. 接收业务层信号，更新界面显示
 * 
 * 特点：
 * - 不包含任何业务逻辑
 * - 通过SerialManager处理所有串口操作
 * - 界面与逻辑完全分离
 */
class SerialWidget : public QWidget
{
    Q_OBJECT

public:
    explicit SerialWidget(QWidget *parent = nullptr);
    ~SerialWidget();
    
    /**
     * @brief 清理资源（返回主页时调用）
     * 关闭串口连接，避免后台继续占用资源
     */
    void cleanup();
    
protected:
    bool eventFilter(QObject *obj, QEvent *event) override;

private:
    void setupUI();
    void connectSignals();
    void updateUIState(bool connected);
    void scanSerialPorts();
    SerialConfig getConfigFromUI() const;

private slots:
    // UI控件响应
    void onRefreshPorts();
    void onOpenPort();
    void onClosePort();
    void onSendData();
    void onClearReceive();
    void onClearSend();
    void onClearStatistics();
    void onAutoSendToggled(bool checked);
    
    // 业务层信号响应
    void onDataReceived(const QByteArray &data);
    void onPortOpened();
    void onPortClosed();
    void onError(const QString &error);
    void onStatisticsUpdated(quint64 rxCount, quint64 txCount);

private:
    // 业务层对象
    SerialManager *m_serialManager;
    SimpleKeyboard *m_keyboard;  // 简单虚拟键盘
    
    // 配置控件
    QComboBox *m_portComboBox;
    QComboBox *m_baudRateComboBox;
    QComboBox *m_dataBitsComboBox;
    QComboBox *m_stopBitsComboBox;
    QComboBox *m_parityComboBox;
    QPushButton *m_refreshButton;
    QPushButton *m_openButton;
    QPushButton *m_closeButton;
    QLabel *m_statusLabel;
    QLabel *m_errorLabel;  // 错误提示标签
    
    // 接收区控件
    QTextEdit *m_receiveTextEdit;
    QCheckBox *m_hexDisplayCheckBox;
    QCheckBox *m_autoWrapCheckBox;
    QCheckBox *m_showTimeCheckBox;
    QPushButton *m_clearReceiveButton;
    
    // 发送区控件
    QTextEdit *m_sendTextEdit;
    QCheckBox *m_hexSendCheckBox;
    QCheckBox *m_addNewlineCheckBox;
    QCheckBox *m_autoSendCheckBox;
    QCheckBox *m_enableKeyboardCheckBox;  // 启用虚拟键盘
    QSpinBox *m_autoSendIntervalSpinBox;
    QPushButton *m_sendButton;
    QPushButton *m_clearSendButton;
    
    // 统计信息
    QLabel *m_rxCountLabel;
    QLabel *m_txCountLabel;
    QPushButton *m_clearStatsButton;
};

#endif // SERIALWIDGET_H
